<template>
	<gui-page ref="guiPage" :customHeader="true">
		<!-- 导航 -->
		<template v-slot:gHeader>
			<nav-bar-custom left-icon="left" :leftType="'1'" @clickLeftBack="clickLeftBack"
				:title="$t('stockManage.pageTitle2')" scanType="0"></nav-bar-custom>
		</template>
		<template v-slot:gBody>
			<view class="barcodeSplitting" :style="'height: calc(100vh - ' + navHeight + 'px);'">
				<view class="custom-form-card">
					<view class="custom-card-title">
						<text class="title-line"></text>
						{{ $t('distributedEnter.barcodeScan') }}
					</view>
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="item-info-title"><text class="required-color">*</text>{{ $t('taskList.tankNumber')
							}}：</text>
						<comboGrid ref="comboGridRef" v-model="data.tankNname" :requestParam="data.requestParam"
							requestUrl="/api1/wms/process/GetProcessLocationByPrdLineId" :calculate="false"
							:placeholder="$t('distributedEnter.placeholderTextChoose')" inputKey="locationCode"
							:column="data.columnRule.column" bindValue="locationName" @setClick="getRuleClick">
						</comboGrid>
					</view>
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="item-info-title"><text class="required-color">*</text>{{
							$t('taskList.tankNumberScan')
						}}：</text>
						<uni-easyinput class="uni-mt-5" suffixIcon="scan" v-model="data.tankNoScan"
							:placeholder="$t('taskList.tankNumberScan')" @confirm="confirmTankNo"
							@iconClick="iconClickTankNo">
						</uni-easyinput>
					</view>
					<!-- <view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="item-info-title">{{ $t('hardware.thisWarehousingQty') }}：</text>
						<uni-easyinput type="text" class="uni-mt-5" v-model="data.inQty"  />
					</view> -->
				</view>
				<!-- <scroll-view :show-scrollbar="false" :scroll-y="true" class="scroll"> -->
				<view v-if="data.scanInfo" class="custom-form-card">
					<uni-collapse v-model="data.value">
						<uni-collapse-item titleBorder="none" :show-animation="true">
							<template v-slot:title>
								<view class="custom-card-title">
									<text class="title-line"></text>
									{{ $t('taskList.currentTankInfor') }}
								</view>
							</template>
							<view class="content">
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{
										$t('distributedEnter.materialCode') }}：</text>{{ data.scanInfo?.materialCode }}
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{
										$t('distributedEnter.materialName') }}：</text>{{ data.scanInfo?.materialName }}
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('distributedEnter.materialSpec') }}：</text>{{
										data.scanInfo?.specification }}
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('distributedEnter.qty') }}：</text>{{
										data.scanInfo?.conversionQty }}
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('distributedEnter.uom') }}：</text>{{
										data.scanInfo?.prdUnit }}
								</view>
								<view class="custom-card-itemOne" style="padding: 20rpx 0;">
									<text class="item-info-title" style="color:red">{{ $t('hardware.thisWarehousingQty')
										}}：</text>
									<uni-easyinput type="number" class="uni-mt-5" v-model="data.scanInfo.inQty"
										style="width:90%" :placeholder="$t('hardwareOut.pleaseQty')"
										 @input="inputClick"/>
									{{ data.materielUnit }}
								</view>
							</view>
						</uni-collapse-item>
					</uni-collapse>
				</view>
				<!-- </scroll-view> -->
				<!-- 底部确定按钮 -->
				<view class="page-bottom-box">
					<view class="page-bottomBtn bottomBtn-bgcolor-green" @click="confirmFn">{{ $t('calendar.submit')
						}}
					</view>
				</view>
				<!-- 页面弹框 -->
				<uni-popup ref="inputDialog" type="center" :mask-click="false">
					<view class="input-dialog-box">
						<view class="input-dialog-content">
							<view class="input-dialog-item">
								<text>{{ $t('taskList.tankNumber') }}：</text>{{ data.scanInfo?.tankNoScan }}
							</view>
							<view class="input-dialog-item">
								<text>{{ $t('distributedEnter.materialCode') }}：</text>{{ data.scanInfo?.materialCode }}
							</view>
							<view class="input-dialog-item">
								<text>{{ $t('hardware.thisWarehousingQty') }}：</text>{{ data.scanInfo?.inQty }}
							</view>
							<view class="input-dialog-item">
								<text>{{ $t('distributedEnter.uom') }}：</text>{{ data.scanInfo?.prdUnit }}
							</view>
						</view>
						<view class="input-dialog-footer">
							<view class="input-dialog-button" @click="cancelFn">
								{{ $t('calendar.cancel') }}
							</view>
							<view class="input-dialog-button dialog-button-left" @click="handelCommit">
								{{ $t('calendar.confirm') }}
							</view>
						</view>
					</view>
				</uni-popup>
			</view>
		</template>
	</gui-page>
</template>

<script setup>
import { navigate, navigateBack } from '@/utils/routerSkip.js';
import pdaScan from '@/hooks/pdaScan.js'
import { useStore } from "vuex";
import { DEFAULT_WAREHOUSECODE, DEFAULT_WAREHOUSEID, OPERATION_COMMIT, OPERATION_SCAN } from '@/constant/index.js'
import { getDataDictionaryFn } from '@/utils/index.js'
import storageBin from '@/components/storageBin.vue'
import comboGrid from '@/components/comboGrid.vue'
import { onShow } from '@dcloudio/uni-app';
import { basPdaOperationLogFn } from '@/utils/index.js';
import { getBaseDataTank, getProcessLocationByPrdLineId, getMaterials, iOTOutputDataEntry } from '@/api/api.js'
import { ref, reactive, onMounted, watch, computed, toRaw } from 'vue';
import { onBackPress } from '@dcloudio/uni-app';

//JS国际化引入
import { useI18n } from 'vue-i18n';
const { t } = useI18n();
let inputDialog = ref(null)

components: {
	storageBin,
		comboGrid
}
const storageBinRef = ref(null)
const comboGridRef = ref(null)
let store = useStore();
const navHeight = computed(() => {
	return store.state.navHeight
})
const { scan } = pdaScan()

const data = reactive({
	value: ['0'],
	tankNo: '',//罐体号
	tankNoScan: '', // 扫描
	inQty: null,//本次入库数量
	requestParam: {
		prdLinecode: 'BigMaterialLine',
		isPD: true,
	},
	columnRule: {
		column: [{
			label: t('taskList.tankName'),
			name: "locationName",
		}, {
			label: t('taskList.tankNumber'),
			name: "locationCode",
		}]
	},
	scanInfo: undefined,
	materielList: [],
	materielUnit: 'kg',
	multiplier: 1,
})

onMounted(() => {
	filter()
})

// 数据字典获取是否存在物料
const filter = async () => {
	await getDataDictionaryFn('ChangeToKg').then(res => {
		if (res.code == 0) {
			data.materielList = res.data
		}
	})
}
// 下拉选择
const getRuleClick = (x) => {
	// console.log(x)
	// 选择赋值
	data.tankNo = x.locationCode
	data.tankNname = x.locationName
	data.tankNoScan = x.locationCode
	data.scanInfo = x
	data.scanInfo.tankNoScan = x.locationCode
	// 获取物料信息
	selectMateriel()
}

//输入框值改变的时候
const inputClick = (e) => {
	console.log(e)
	if(e<0){
		data.scanInfo.inQty= e.replace(/\D/g, '')
		data.scanInfo.conversionQty = Math.abs(e) * data.multiplier
	}else{
		data.scanInfo.conversionQty = e * data.multiplier
	}
	console.log('Math.abs(e)',data.scanInfo.inQty)
}

// 查询物料
const selectMateriel = () => {
	let parmes = {
		processCode: 'YH',
		lineCode: 'BigMaterialLine',
		locationCode: data.tankNo
	}
	getBaseDataTank(parmes).then(res => {
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '大料入库'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.code,//返回状态
				errorMessage: res.msg,//错误信息
				isPass: res.code == 200 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_SCAN,
				module: 'WMS',
				source: "PDA",
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		if (res.code == 200) {
			let x = res.result[0]
			let arr = data.materielList.filter(a => a.value == x.materialCode)
			console.log('arr', arr)
			if (arr.length > 0) {
				data.materielUnit = 'LBS'
				data.multiplier = Number(arr[0].remark)
			} else {
				data.materielUnit = 'kg'
				data.multiplier = 1
			}
			// 获取物料规格
			getMaterials({
				current: 1,
				size: 10,
				materialCode: x.materialCode,
				text: " "
			}).then(res => {
				if (res.code == 0) {
					data.scanInfo.materialCode = x.materialCode
					data.scanInfo.materialName = x.materialName
					data.scanInfo.prdUnit = x.prdUnit
					data.scanInfo.specification = res.data.records[0].specification
					data.scanInfo.qty = x.qty
					data.scanInfo.inQty = null
				}
			})
		}else{
			uni.showToast({
                title: res.msg,
                icon: 'none',
                duration: 2000
            })
		}
	})
}

// 扫描罐体
const confirmTankNo = () => {
	getCode(data.tankNoScan, 'keydown')

}
const iconClickTankNo = async () => {
	if (type === 'suffix') {
		let code = await scan()
		getCode(code, 'scan')
	}
}

const getCode = (code, type) => {
	data.tankNoScan = code
	var parmes = {
		prdLinecode: 'BigMaterialLine',
		isPD: true,
		locationCode: code,
		current: 1,
		size: 20,
	}
	// 调用接口
	getProcessLocationByPrdLineId(parmes).then(res => {
		if (res.code == 0) {
			if(res.data.records.length>0){
				data.tankNo = res.data.records[0].locationCode
				data.tankNname = res.data.records[0].locationName
				data.scanInfo = res.data.records[0]
				selectMateriel()
			}else{
				data.tankNoScan=''
				uni.showToast({
					title: t('fixedAssets.scanTankExist'),icon: 'none',
				})
			}
		}else{
			uni.showToast({
                title: res.msg,icon: 'none'
            })
		}

	})
}

//生成随机id
const generateRandomNum = () => {
	const timestamp = new Date().getTime();
	const randomNum = uuid();
	return timestamp.toString() + '-' + randomNum.toString();
}
const uuid = () => {
	return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
		var r = Math.random() * 16 | 0,
			v = c == 'x' ? r : (r & 0x3 | 0x8);
		return v.toString(16);
	});
}

const dateListEnd = () => {
	let year = new Date().getFullYear()
	let month = ((new Date().getMonth() + 1) > 10 ? (new Date().getMonth() + 1) : '0' + (new Date().getMonth() + 1))
	let date = new Date().getDate()
	let currentTime = new Date().toLocaleTimeString();
	let milliseconds = new Date().getMilliseconds(); // 毫秒
	return year + '-' + month + '-' + date + ' ' + currentTime
}
// 提交打开弹框
const confirmFn = () => {
	inputDialog.value.open();
}
// 点击取消
const cancelFn = () => {
	inputDialog.value.close();
}
//弹框确定 提交
const handelCommit = () => {
	if (!data.scanInfo) {
		uni.showToast({ title: t('taskList.scanTankOrSelect'), icon: "none" });
		return
	}
	if (data.scanInfo?.inQty <= 0) {
		uni.showToast({ title: t('Common.inputNumber'), icon: "none" });
		return
	}
	//调用接口
	let parmes = {
		lstTransferDto: []
	}
	parmes.lstTransferDto.push({
		batch_no: 1,
		batch_count: 1,
		production_line_code: 'BigMaterialLine',
		production_line_name: '大料产线',
		process_code: 'YH',
		process_name: '预混',
		location_type: 'PDLocation',
		location_code: data.scanInfo.locationCode,
		location_name: data.scanInfo.locationName,
		material_code: data.scanInfo.materialCode,
		material_name: data.scanInfo.materialName,
		qty: data.scanInfo.conversionQty,//data.scanInfo.inQty
		produce_start_time: null,
		produce_end_time:  null,
		prd_unit: data.scanInfo.prdUnit,
		operate_type: 'BigMaterialInstock',
		operate_desc: 'BigMaterial instock',
		uuid: generateRandomNum(),
		is_current_location: 'N',
		is_wrap: 'N',
		is_band: 'N',
	})
	// 添加加载框
	uni.showLoading({
		title: 'loading',
		mask: true
	});
	iOTOutputDataEntry(parmes).then(res => {
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '大料入库'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.code,//返回状态
				errorMessage: res.msg,//错误信息
				isPass: res.code == 200 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_COMMIT,
				module: 'WMS',
				source: "PDA",
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		if (res.code == 200) {
			uni.showToast({ title: t('smashRemoval.submitSuccessfully'), icon: "none" });
			//隐藏加载框
			uni.hideLoading();
			data.scanInfo = undefined
			data.tankNo = ''
			data.tankNname = ''
			data.tankNoScan = ''
			inputDialog.value.close();
		} else {
			uni.showToast({ title: res.msg, icon: "none" });
		}
	})
}

//导航栏左侧返回
const clickLeftBack = () => {
	if (!data.scanInfo.length) {
		uni.navigateBack({
			delta: 1
		});
		return
	}
	uni.showModal({
		title: t('smashRemoval.warmPrompt'),
		content: t('materials.clearedIfReturned'),
		success: function (res) {
			if (res.confirm) {
				data.scanInfo = undefined
				uni.navigateBack({
					delta: 1
				});
			} else if (res.cancel) {
				console.log('用户点击取消');
			}
		}
	});
}

onBackPress((options) => {
	if (options.from == 'backbutton') {
		if (!data.scanInfo.length) {
			uni.navigateBack({
				delta: 1
			});
			return true
		}
		uni.showModal({
			title: t('smashRemoval.warmPrompt'),
			content: t('materials.unsubmittedDataIn'),
			success: function (res) {
				if (res.confirm) {
					data.scanInfo = undefined
					uni.navigateBack({
						delta: 1
					});
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
		return true;
	}
})
</script>

<style lang="scss" scoped>
.barcodeSplitting {
	display: flex;
	flex-direction: column;
	height: calc(100vh - 88rpx);
	// height: 100vh;
}

.distributed-head {
	border-bottom-left-radius: 16rpx;
	border-bottom-right-radius: 16rpx;
}

.scroll {
	flex: 1;
	height: 2rpx;
}

.page-bottom-box {
	position: absolute;
	left: 0px;
	bottom: 0px;
	width: 100%;
}
</style>
